const {
  CurrencyShopModel
} = require('../../../utils/currencyshop-model.js')
const currencyShopModel = new CurrencyShopModel()
const {
  SvipModel
} = require('../../../utils/svip-model.js')
const svipModel = new SvipModel()
const {
  MemberModel
} = require('../../../utils/member-model.js');
var memberModel = new MemberModel();
const {
  Config
} = require('../../../utils/config.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopName: '',
    address: '',
    shopId: '',
    currencies: [],
    modelShow: false,
    tabs: [{
        label: '游戏币',
        value: 0
      },
      {
        label: '游戏券',
        value: 1
      },
      {
        label: '币券套餐',
        value: 2
      }
    ],
    tabIdx: 0
  },

  tabChange(e) {
    const index = e.currentTarget.dataset.index
    if (index !== this.data.tabIdx) {
      this.setData({
        tabIdx: index
      })
      switch (index) {
        case 0:
          this.getCurrency();
          break;
        case 1:
          this.getPreviewVersion().then(() => {
            this.getGamecoupon();
          }).catch(() => {
            this.setData({
              currencies: []
            })
          })
          break;
        default:
          this.getPreviewVersion().then(() => {
            this.getGamecouponpackage();
          }).catch(() => {
            this.setData({
              currencies: []
            })
          })
      }
    }
  },

  getPreviewVersion() {
    return new Promise((resolve, reject) => {
      svipModel.previewVersion({
        merchantId: wx.getStorageSync('merchantId'),
        appId: Config.appId
      }).then(data => {
        if (data === 'wx_yxq') {
          reject(false)
        } else {
          resolve(true)
        }
      }).catch(err => {
        reject(false)
      })
    })
  },

  goCommitOrder(e) {
    let currency = e.currentTarget.dataset.currency
    wx.navigateTo({
      url: `/pages/currencyShop/currencyDetail/index?shopName=${this.data.shopName}&currency=${encodeURIComponent(JSON.stringify(currency))}&shopId=${this.data.shopId}&type=${this.data.tabIdx}`
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.shopId && options.shopName && options.address) {
      this.setData({
        address: options.address,
        shopName: options.shopName,
        shopId: options.shopId,
        modelShow: true
      })
    } else {
      const shopInfo = wx.getStorageSync('shopInfo')
      this.setData({
        address: shopInfo.address,
        shopName: shopInfo.shopName,
        shopId: shopInfo.shopId,
        modelShow: true
      })
    }
    this.getCurrency()
  },
  getCurrency() {
    const merchantId = wx.getStorageSync('merchantId')
    currencyShopModel.getCurrencyv2({
      merchantId,
      shopId: this.data.shopId,
    }).then(data => {
      const currencies = (data || []).map(item => {
        item.satisfyActivityTypeList = item.satisfyActivityTypeList || []
        let rightsType = 0
        if (item.goodsTags && item.goodsTags != null && item.goodsTags.length > 0) {
          item.goodsTags.forEach(element => {
            if (element.goodsTagId === 'dwj_svip') {
              rightsType = 1
            }
          })
        }
        if (rightsType === 1 || !item.satisfyActivityTypeList.length) {
          item.satisfyActivityTypeList = []
        } else if (item.satisfyActivityTypeList.length === 1) {
          item.satisfyActivityTypeList = item.satisfyActivityTypeList
        } else if (item.satisfyActivityTypeList.length === 2 && item.satisfyActivityTypeList.includes(7) && item.satisfyActivityTypeList.includes(8)) {
          item.satisfyActivityTypeList = [8]
        } else {
          item.satisfyActivityTypeList = [5]
        }
        let commodityPrices = 0;
        const goodsPrices = item.goodsPrices.map(price => {
          const split = price.amount.toFixed(2).split('.')
          if (price.priceType === 0) {
            commodityPrices = price.amount
          }
          return {
            ...price,
            int: split[0],
            float: split[1]
          }
        })
        return {
          ...item,
          goodsPrices,
          rightsType,
          commodityPrices
        }
      })
      currencyShopModel.getConfig({
        merchantId,
        shopId: this.data.shopId,
        dictKeys: 'viewProductSwitch'
      }).then(data => {
        if (data.viewProductSwitch != '1') {
          this.setData({
            currencies: currencies.filter(item => item.commodityPrices < 200)
          })
        } else {
          this.setData({
            currencies
          })
        }
      }).catch(() => {
        this.setData({
          currencies
        })
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },
  getGamecoupon() {
    const merchantId = wx.getStorageSync('merchantId')
    currencyShopModel.getGamecouponv2({
      merchantId,
      shopId: this.data.shopId
    }).then(data => {
      const currencies = (data || []).map(item => {
        item.satisfyActivityTypeList = item.satisfyActivityTypeList || []
        let rightsType = 0
        if (item.goodsTags && item.goodsTags != null && item.goodsTags.length > 0) {
          item.goodsTags.forEach(element => {
            if (element.goodsTagId === 'dwj_svip') {
              rightsType = 1
            }
          })
        }
        if (!item.satisfyActivityTypeList.length) {
          item.satisfyActivityTypeList = []
        } else if (item.satisfyActivityTypeList.length === 1) {
          item.satisfyActivityTypeList = item.satisfyActivityTypeList
        } else if (item.satisfyActivityTypeList.length === 2 && item.satisfyActivityTypeList.includes(7) && item.satisfyActivityTypeList.includes(8)) {
          item.satisfyActivityTypeList = [8]
        } else {
          item.satisfyActivityTypeList = [5]
        }
        const goodsPrices = item.goodsPrices.map(price => {
          const split = price.amount.toFixed(2).split('.')
          return {
            ...price,
            int: split[0],
            float: split[1]
          }
        })
        return {
          ...item,
          goodsPrices,
          rightsType
        }
      })
      this.setData({
        currencies
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },
  getGamecouponpackage() {
    const merchantId = wx.getStorageSync('merchantId')
    currencyShopModel.getGamecouponpackagev2({
      merchantId,
      shopId: this.data.shopId
    }).then(data => {
      const currencies = (data || []).map(item => {
        item.satisfyActivityTypeList = item.satisfyActivityTypeList || []
        let rightsType = 0
        if (item.goodsTags && item.goodsTags != null && item.goodsTags.length > 0) {
          item.goodsTags.forEach(element => {
            if (element.goodsTagId === 'dwj_svip') {
              rightsType = 1
            }
          })
        }
        if (!item.satisfyActivityTypeList.length) {
          item.satisfyActivityTypeList = []
        } else if (item.satisfyActivityTypeList.length === 1) {
          item.satisfyActivityTypeList = item.satisfyActivityTypeList
        } else if (item.satisfyActivityTypeList.length === 2 && item.satisfyActivityTypeList.includes(7) && item.satisfyActivityTypeList.includes(8)) {
          item.satisfyActivityTypeList = [8]
        } else {
          item.satisfyActivityTypeList = [5]
        }
        const goodsPrices = item.goodsPrices.map(price => {
          const split = price.amount.toFixed(2).split('.')
          return {
            ...price,
            int: split[0],
            float: split[1]
          }
        })
        return {
          ...item,
          goodsPrices,
          rightsType
        }
      })
      this.setData({
        currencies
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
  },
  closeModel: function () {
    let that = this
    that.setData({
      modelShow: false
    })
    that.getSubscribeMessage();
  },

  /**
   * 1.点击【我知道了】显示订阅消息弹窗
   * 2.点击【积分商城】进入积分详情页面时
   * 3.会员授权成功后
   * 4.点击【会员中心】按钮
   */
  getSubscribeMessage: function () {
    memberModel.subscribeMessage({
      merchantId: wx.getStorageSync('merchantId'),
      position: 1
    }).then(data => {
      if (data && data.length > 0) {
        let tmplId = []
        data.forEach(element => {
          tmplId.push(element.templateId)
        })
        wx.requestSubscribeMessage({
          tmplIds: tmplId,
          success(res) {},
          fail(err) {}
        })
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})